package com.zlzxm.shoesmarket.globle;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.tencent.mmkv.MMKV;

import java.util.List;

/**
 * CREATE BY zlzxm ON 2021/5/13
 */
public class UserManager {

    public static String TIP = "账号未登录,请先登录";

    public static class Repository{

        private String id;

        private String name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }


    public static class User{

        private String id;

        private String token;

        private List<Repository> repositories;

        public User(String id, String token) {
            this.id = id;
            this.token = token;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public List<Repository> getRepositories() {
            return repositories;
        }

        public void setRepositories(List<Repository> repositories) {
            this.repositories = repositories;
        }
    }

    private UserManager() {

        String user  = MMKV.defaultMMKV().decodeString(Constant.MMKVKey.USER);

        if (!TextUtils.isEmpty(user)){

            Gson gson = new Gson();

            this.user = gson.fromJson(user,User.class);

        }

    }

    public static class Hold {

        private static UserManager userManager = new UserManager();

    }

    public static  UserManager getInstance(){

        return Hold.userManager;
    }


    private User user;


    public boolean isLogin(){

        return  user != null;
    }

    public void login(String id, String token){

        User user = new User(id,token);

        login(user);

    }


    public void login(User user){

        this.user = user;

        saveUser(user);

    }

    public void loginOut(){

        this.user = null;
        clearUser();
    }

    public String getId(){


        return user==null?null: user.getId();
    }


    public User getUser() {
        return user;
    }

    public String getToken(){


        return user==null?null: user.getToken();
    }

    public List<Repository> getRepository(){

        return user==null?null: user.getRepositories();
    }


    public void saveUser(User user){

        Gson gson = new Gson();

        String json = gson.toJson(user);

        MMKV.defaultMMKV().encode(Constant.MMKVKey.USER,json);

    }

    private void clearUser(){

        MMKV.defaultMMKV().remove(Constant.MMKVKey.USER);
    }


}
